import { List, Modal, message } from "antd";
import { useEffect, useState } from "react";
import { getCollectionApi, getToken } from "../utils/client";
import CodeEditor from '@uiw/react-textarea-code-editor';

export interface ShowIndexModalProps {
    curClientId: string;
    curDatabase: string;
    collection: string;
    onCancel: () => void;
}

function ShowIndexModal(props: ShowIndexModalProps) {

    const [indexList, setIndexList] = useState<string[]>([]);

    const loadIndexList = async () => {
        const client = getCollectionApi();
        try {
            const res = await client.viewListPost({
                viewListPostRequest: {
                    token: getToken(),
                    id: props.curClientId,
                    database: props.curDatabase,
                    collection: props.collection,
                },
            });
            setIndexList(res);
        } catch (e) {
            console.log(e);
            message.error("无法获取索引信息");
        }
    };

    const getIndexContent = (index: string) => {
        const obj = JSON.parse(index);
        return JSON.stringify(obj, null, 2);
    };

    useEffect(() => {
        loadIndexList();
    }, [props.curClientId, props.curDatabase, props.collection]);

    return (
        <Modal open title="数据表索引" footer={null}
            bodyStyle={{ maxHeight: "calc(100vh - 300px)", overflowY: "auto", paddingRight: "20px" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}>
            <List dataSource={indexList} renderItem={index => (
                <List.Item key={index}>
                    <CodeEditor
                        value={getIndexContent(index)}
                        language="json"
                        minHeight={200}
                        readOnly={true}
                        style={{
                            fontSize: 14,
                            backgroundColor: '#f5f5f5',
                            width: "100%"
                        }}
                    />
                </List.Item>
            )} />
        </Modal>
    );
}

export default ShowIndexModal;